package com.student.Activitys.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.student.Activitys.R;
import com.student.Activitys.activity.base.BaseActivity;
import com.student.Activitys.adapter.SupportApplyExpandableAdapter;
import com.student.Activitys.bean.InfoReturnBean;
import com.student.Activitys.bean.UserBean;
import com.student.Activitys.bean.pack.SupportApplyPack;
import com.odd.Activitys.http.manager.SupportManager;
import com.student.Activitys.utils.AccountValidatorUtils;
import com.student.Activitys.utils.Constant;
import com.student.Activitys.utils.ToastUtils;
import com.student.Activitys.view.PinnedHeaderExpandableListView;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：智慧校园学生端
 * 类描述：奖学金申请
 * 创建人：张飞祥
 * 创建时间：2017/10/12 9:47
 * 修改人：张飞祥
 * 修改时间：2017/10/12 9:47
 * 修改备注：
 */
public class SupportApplyActivity extends BaseActivity {

    @Bind(R.id.iv_return)
    ImageView ivReturn;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.ex_list_support_apply)
    PinnedHeaderExpandableListView exListSupportApply;
    @Bind(R.id.tv_support_apply_title)
    TextView tvSupportApplyTitle;
    @Bind(R.id.btn_support_apply_submit)
    Button btnSupportApplySubmit;

    //适配器
    private SupportApplyExpandableAdapter adapter = null;
    //数据源
    private List<SupportApplyPack> list = null;
    //父布局标题
    private List<String> titles = null;
    //当前用户
    private UserBean user = null;
    //当前奖惩状态
    private String type;
    //当前奖惩id
    private String id;
    //当前奖惩 标题
    private String title;
    //初始化网络请求
    public SupportManager mApiManager;
    //弹窗 diaolog
    public MaterialDialog msgDialog;

    @Override
    protected void initUI() {
        setContentView(R.layout.act_support_apply);
        //网络请求 常驻方法
        mApiManager = mApiManager.getSupportApiManager(SupportApplyActivity.this, SupportApplyActivity.this.getTaskId());
        // 获取传递过来的封了数据的Bundle
        Bundle bundle = this.getIntent().getExtras();
        // 获取 传递过来的 奖惩状态
        type = bundle.getString("type");
        // 获取 传递过来的 奖惩id
        id = bundle.getString(Constant.WEB_ID);
        // 获取 传递过来的 奖惩 标题
        title = bundle.getString(Constant.WEB_TITLE);
        //显示返回按钮
        ivReturn.setVisibility(View.VISIBLE);
        list = new ArrayList<>();
        //获取当前用户
        /**
         * 创建 Gson 解析储存的用户数据 反填 界面数据
         */
        Gson gson = new Gson();
        user = gson.fromJson(mACache.getAsJSONObject(Constant.USER) + "", UserBean.class);
    }

    @Override
    protected void initData() {
        //奖惩 标题
        tvSupportApplyTitle.setText(title);
        /**
         * 奖学金
         */
        if (type.equals(Constant.SUPPORT_SCHOLARSHIP)) {
            //设置标题
            tvTitle.setText("奖学金申请");
            //设置父布局标题
            titles = new ArrayList<>();
            titles.add("个人信息");
            titles.add("上学年成绩及获奖情况");
            titles.add("在校表现");
            //设置按钮样式 “橙色”
            btnSupportApplySubmit.setBackgroundResource(R.drawable.public_btn_orange_selected);
            //设置 文字左侧 图片
            Drawable drawable = getResources().getDrawable(R.drawable.ic_text_orange_left);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            tvSupportApplyTitle.setCompoundDrawables(drawable, null, null, null);
        }

        /**
         * 助学金
         */
        if (type.equals(Constant.SUPPORT_A_GRANT)) {
            //设置标题
            tvTitle.setText("助学金申请");
            //设置父布局标题
            titles = new ArrayList<>();
            titles.add("个人信息");
            titles.add("家庭情况收入");
            titles.add("申请理由");
            //设置按钮样式 “红色”
            btnSupportApplySubmit.setBackgroundResource(R.drawable.public_btn_red_selected);
            //设置 文字左侧 图片
            Drawable drawable = getResources().getDrawable(R.drawable.ic_text_red_left);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            tvSupportApplyTitle.setCompoundDrawables(drawable, null, null, null);
        }

        for (int i = 0; i < titles.size(); i++) {
            SupportApplyPack pack = new SupportApplyPack();
            if (i == 0) {
                pack.setUser(user);
            }
            pack.setName(titles.get(i));
            pack.setType(i + 1);

            list.add(pack);
        }
        //设置悬浮头部VIEW
        exListSupportApply.setHeaderView(getLayoutInflater().inflate(R.layout.item_pulic_group_head, exListSupportApply, false));
        adapter = new SupportApplyExpandableAdapter(list, SupportApplyActivity.this, exListSupportApply, type);
        exListSupportApply.setAdapter(adapter);
    }

    @Override
    protected void getNotData() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_return, R.id.btn_support_apply_submit})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:                   //退出
                finish();
                break;
            case R.id.btn_support_apply_submit:    //申请
                setDateSubmit();
                break;
        }
    }

    /**
     * 数据提交
     */
    private void setDateSubmit() {

        //获取最新 adapter 发生变化的数据
        List<SupportApplyPack> adapterList = adapter.getAdapterList();
        //获取用户信息
        UserBean adapterUser = adapterList.get(0).getUser();
        //获取 第一个富文本
        String situation = adapterList.get(1).getSituation();
        //获取 第二个富文本
        String expression = adapterList.get(2).getExpression();

        /**
         * 判断 列表 （家庭住址、第一个富文本、第二个富文本）不允许为空，才可以请求
         */
        if ("".equals(situation) || situation == null ||
                "".equals(expression) || expression == null ||
                "".equals(adapterUser.getMobile()) || adapterUser.getMobile() == null ||
                "".equals(adapterUser.getSFZH()) || adapterUser.getSFZH() == null ||
                "".equals(adapterUser.getFamilyAddr()) || adapterUser.getFamilyAddr() == null) {
            ToastUtils.showShort(SupportApplyActivity.this, "请完善您的信息情况~");
        } else if (!AccountValidatorUtils.isMobile(adapterUser.getMobile())) {
            ToastUtils.showShort(SupportApplyActivity.this, "手机号码格式不正确！");
        } else if (!AccountValidatorUtils.isEmail(adapterUser.getMail())) {
            ToastUtils.showShort(SupportApplyActivity.this, "邮箱格式不正确！");
        } else {
            //提交数据
            initHttp(adapterUser, situation, expression);
        }
    }

    /**
     * 开始网络请求
     */
    private void initHttp(UserBean adapterUser, String situation, String expression) {

        //请求日课表数据
        mApiManager.supportApply(Constant.HTTP_SUPPORT_SUBMIT_ACTION, adapterUser.getXH(), id, type,
                adapterUser.getMobile(), adapterUser.getMail(), adapterUser.getQQ(), adapterUser.getWeixin(),
                adapterUser.getFamilyAddr(), adapterUser.getSFZH(), situation, expression);

        //显示 加载dialog
        initShowTimeDialog("正在提交申请，请稍后...",SupportApplyActivity.this);
    }

    /**
     * 奖惩：数据提交 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_SUPPORT_SUBMIT_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initAddress(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 奖惩：数据提交 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_SUPPORT_SUBMIT, mode = ThreadMode.MAIN)
    public void initAddress(InfoReturnBean bean) {
        msgDialog = new MaterialDialog.Builder(SupportApplyActivity.this)
                .title("成功")
                .content(bean.getMsg())
                .positiveText("确认")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        finish();
                    }
                }).show();
        // 设置点击屏幕Dialog不消失
        msgDialog.setCanceledOnTouchOutside(false);
        //取消Back键监听
        msgDialog.setCancelable(false);
    }
}
